<template>
  <div class="home-container">
    <el-container>
      <el-header>
        <el-menu
          :default-active="activeIndex"
          class="el-menu-demo"
          mode="horizontal"
        >
          <el-menu-item index="1" @click="navigateTo('/home')">
            商店主页
          </el-menu-item>
          <el-menu-item index="2" @click="navigateTo('/cart')">
            购物车
          </el-menu-item>
        </el-menu>
      </el-header>

      <el-main>
        <!-- 订单表格 -->
        <div class="CartBox">
          <h1>{{ username }}的订单</h1>
          <el-table
            ref="multipleTable"
            :data="OrderData"
            tooltip-effect="dark"
            style="width: 100%; font-size: 20px"
            @selection-change="handleSelectionChange"
          >
            <el-table-column width="40"></el-table-column>
            <el-table-column label="商品图片" width="200">
              <template #default="scope">
                <img
                  :src="scope.row.image"
                  alt="SmallImage"
                  class="resized-image"
                />
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              label="商品名称"
              width="350"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column
              prop="price"
              label="单价"
              width="140"
            ></el-table-column>
            <el-table-column
              prop="quantity"
              label="数量"
              width="100"
            ></el-table-column>
            <el-table-column label="小计" width="180">
              <template #default="scope">
                <div class="TotalPrice">
                  {{ scope.row.price * scope.row.quantity }}元
                </div>
              </template>
            </el-table-column>
            <el-table-column label="购买时间" width="200">
              <template #default="scope">
                {{ formatDate(scope.row.purchaseTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="140">
              <template #default="scope">
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  @click="deleteCart(scope.row.id)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
export default {
  name: 'OrderHistory',
  data() {
    return {
      activeIndex: '0',
      OrderData: [],
      username: '',
    }
  },
  mounted() {
    this.getOrderData()
    this.getUsername()
  },
  methods: {
    //导航栏跳转
    navigateTo(path) {
      this.$router.push(path)
    },
    // 格式化时间为可读的形式
    formatDate(dateStr) {
      const date = new Date(dateStr) // 将字符串转换为 Date 对象
      return date.toLocaleString() // 使用浏览器的默认格式输出时间（日期和时间）
    },
    //获取用户名
    getUsername() {
      const token = localStorage.getItem('jwtToken') // 获取存储的 token

      this.$http
        .get('/api/user/username', {
          headers: {
            Authorization: `Bearer ${token}`, // 使用 Bearer 方案
          },
        })
        .then((res) => {
          this.username = res.data.data
          console.log(this.username)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //删除订单
    async deleteCart(id) {
      try {
        const token = localStorage.getItem('jwtToken') // 获取存储的 token
        const response = await this.$http.delete('/api/cart/' + id, {
          headers: { Authorization: `Bearer ${token}` },
        })
        if (response.data.code === 1) {
          this.multipleSelection = [] // 清空选中的商品
          this.getOrderData() // 重新获取购物车数据，刷新页面
        }
      } catch (error) {
        console.error('删除失败', error)
      }
    },
    //获取订单列表
    getOrderData() {
      const token = localStorage.getItem('jwtToken') // 获取存储的 token

      this.$http
        .get('/api/cart/order', {
          headers: {
            Authorization: `Bearer ${token}`, // 使用 Bearer 方案
          },
        })
        .then((res) => {
          this.OrderData = res.data.data
          console.log(this.OrderData.data)
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style>
.home-container {
  margin: 20px;
}

.el-header {
  display: flex;
  justify-content: center;
}
.el-footer {
  background-color: #bfc7d2;
  color: #333;
  text-align: center;
  line-height: 60px;
}
.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
}
.CartBox {
  margin: 0 134px 0;
  padding: 0px;
  border: 1px solid #ccc;
  border-radius: 5px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.resized-image {
  max-width: 120px;
  max-height: 120px;
  object-fit: contain;
}
.TotalPrice {
  font-size: 20px;
  line-height: 1;
  color: #ff6700;
  padding: 12px 0 10px;
}

.FooterBox {
  display: flex; /* 使用flex布局 */
  justify-content: space-between; /* 让元素分布在两端 */
  align-items: center; /* 垂直居中对齐 */
  margin: 0 134px 0;
  background-color: #b3c0d1;
}
.chose-quantity {
  padding: 0 0px 0px 20px; /* 上右下左 */
  text-align: left;
  width: 200px;
}
.total-price {
  color: #ff6700;
  font-size: 24px;
}
.btn-primary {
  max-height: 60px;
  padding: 15px 40px;
  font-size: 24px;
  margin-left: 20px;
  background: #ff6700;
  border-color: #ff6700;
  color: #fff;
}
</style>